package moodish.client;


import javax.swing.JOptionPane;

import moodish.comm.ClientComm;
import moodish.comm.ClientSideMessage;
import moodish.comm.ClientSideMessage.Type;

public class MessageReader implements Runnable {

        private GUI gui;
        private ClientComm clientComm;

        public MessageReader(GUI gui, ClientComm clientComm) {
                this.gui = gui;
                this.clientComm = clientComm;
        }

        /**
         * Implements the infinite cycle that reads every incoming message
         */
        @Override
        public void run() {
                while (clientComm.isConnected()) {
                        ClientSideMessage msg = clientComm.getNextMessage();
                        if (msg != null) {
                                readMsg(msg);
                        } else {
//                                gui.connectionLost();
//                                return;
                        }
                }
                
                gui.connectionLost();
                
        }

        /**
         * Interprets the message and calls the appropriate GUI methods and/or
         * displays the relevant information to the user
         * 
         * @param msg
         */
        private void readMsg(ClientSideMessage msg) {
                ClientSideMessage.Type type = msg.getType();
                String payLoad = msg.getPayload();
                String senderName = msg.getSendersNickname();

                switch (type) {
                case CONNECTED:
                        if (!payLoad.equals(gui.getUserNickName()))
                                gui.userConnected(payLoad);
                        break;
                case DISCONNECTED:
                        if (payLoad.equals(gui.getUserNickName()))
                                gui.connectionLost();
                        else
                                gui.userDisconnected(payLoad);
                        break;
                case MOODISH_MESSAGE:
                        gui.setMood(senderName, payLoad);
                        break;
                case FRIENDSHIP:
                        JOptionPane.showMessageDialog(gui.getJFrame(), "The user "
                                        + payLoad + " is now your friend");
                        break;
                case UNFRIENDSHIP:
                        JOptionPane.showMessageDialog(gui.getJFrame(), "The user "
                                        + payLoad + " is no longer your friend");
                        break;
                case ERROR:
                        // Falta analisar cada msg de erro
                      
                        break;
                default:
                        break;
                }

        }
}